package com.example.service;

import io.jsonwebtoken.*;
import io.jsonwebtoken.impl.crypto.MacProvider;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Date;

/**
 * Copyright © 2016年 author. All rights reserved.
 *
 * @Author 临江仙 hzqiuxm@163.com
 * @Date 2017/9/30 0030 15:23
 */
public class JjwtDemo {

    public static Key key = MacProvider.generateKey();

    public static void main(String[] args) {



        String compactJws = Jwts.builder()
                .setSubject("hzqiuxm")
                .setIssuer("lvxxun")
                .compressWith(CompressionCodecs.DEFLATE)
                .signWith(SignatureAlgorithm.HS512,key)
                .compact();

        System.out.println("compactJws = " + compactJws);


        if (verifyJWT(compactJws)){

            System.out.println("The JWT is OK! we can trust this JWT.");
        }else {
            System.out.println("We don't trust this JWT!");
        }

//        assert Jwts.parser().setSigningKey(key).parseClaimsJws(compactJws).getBody().getSubject().equals("Joe");
    }

    private static boolean verifyJWT(String compactJws) {
        Jws<Claims> claims = null;

        try {
             claims = Jwts.parser()
                    .requireSubject("qiuxm")
                    .require("hasMotorcycle", true)
                    .setSigningKey(key)
                    .parseClaimsJws(compactJws);

            System.out.println(claims.getHeader().getAlgorithm());
            System.out.println(claims.getBody().getSubject());
            System.out.println(claims.getSignature());


        } catch (MissingClaimException e) {

            // we get here if the required claim is not present
//            e.printStackTrace();
            System.out.println(e.getMessage());

            return false;

        } catch (IncorrectClaimException e) {

            // we get here if the required claim has the wrong value
//            e.printStackTrace();
            System.out.println(e.getMessage());
            return false;

        }

        return true;

    }


    //Sample method to construct a JWT

    /**
     *
     * @param id
     * @param issuer
     * @param subject
     * @param ttlMillis
     * @return
     */
    private String createJWT(String id, String issuer, String subject, long ttlMillis) {

        //The JWT signature algorithm we will be using to sign the token
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);

        //We will sign our JWT with our ApiKey secret
        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary("key");
        Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());

        //Let's set the JWT Claims
        JwtBuilder builder = Jwts.builder().setId(id)
                .setIssuedAt(now)
                .setSubject(subject)
                .setIssuer(issuer)
                .signWith(signatureAlgorithm, signingKey);

        //if it has been specified, let's add the expiration
        if (ttlMillis >= 0) {
            long expMillis = nowMillis + ttlMillis;
            Date exp = new Date(expMillis);
            builder.setExpiration(exp);
        }

        //Builds the JWT and serializes it to a compact, URL-safe string
        return builder.compact();
    }


}
